package cn.edu.zafu.bigdata.x.zbw;

import java.io.*;
import java.net.*;

public class ClockServer {
    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket(9999)) {
            System.out.println("时钟服务器启动，等待客户端请求...");

            while (true) {
                byte[] receiveData = new byte[1024];
                byte[] sendData = new byte[1024];

                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket.receive(receivePacket);

                String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("收到客户端请求: " + sentence);

                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
                long currentTime = System.currentTimeMillis();
                InetAddress IPAddress = receivePacket.getAddress();

                System.out.println("发送当前时间给客户端: " + currentTime);
                String message = "当前时间戳: " + currentTime;
                sendPacket.setData(message.getBytes());

                socket.send(sendPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
